package com.aaron.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.List;

/**
 * @Description
 * @Author Aaron
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/10/30
 */
public class XmlParseMapper {

    private Configuration configuration;

    public XmlParseMapper(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(String path) throws DocumentException,ClassNotFoundException {
        InputStream inputStream = Resource.getResource(path);
        SAXReader reader = new SAXReader();
        Document doc = reader.read(inputStream);

        Element rootElement = doc.getRootElement();
        //获取namespace
        String namespace = rootElement.attributeValue("namespace");
        //解析select
        List<Element> selectList = rootElement.selectNodes("select");
        for (Element e : selectList) {
            String id = e.attributeValue("id");
            String key = namespace+"."+id;
            String resultType = e.attributeValue("resultType");
            String paramType = e.attributeValue("paramType");
            String sqlText = e.getText();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setSqlText(sqlText);
            mappedStatement.setStatement(id);
            Class<?> resultClass = getClassType(resultType);
            Class<?> paramClass = getClassType(paramType);
            mappedStatement.setParamType(paramClass);
            mappedStatement.setResultType(resultClass);
            configuration.getMappers().put(key, mappedStatement);
        }
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        Class<?> aClass = Class.forName(paramterType);
        return aClass;
    }
}
